<?php
namespace API\Controller;
use Common\Tool\Tool;
use API\Model\GoodsCartModel;
use API\Model\GoodsModel;

/**
 * 购物车
 * @author 王强
 * @method $this
 */
class CartController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        
        $this->isLogin();
    }
    //添加到购物车【无分销】
    public function addCart()
    {
        
        Tool::checkPost($_POST, array('is_numeric' => array('goods_id', 'num')), true , array('goods_id', 'num')) ? true : $this->ajaxReturnData(null, '400', '参数错误');
        
//      if ($_SESSION['form'] !== $_POST['form']) { $this->ajaxReturnData(null, 0, '恶意攻击将负法律责任');}
        
        //查询商品信息
        $data = GoodsModel::getInitation()->getGoodsById(array(
           'field' => 'id as goods_id,price_new,fanli_jifen' ,
           'where' => array('id' => $_POST['goods_id'])
        ));
        
        //查无此人
        empty($data) ? $this->ajaxReturnData(null, '400', '没有该商品') : true; 
        
        $data['goods_num'] = $_POST['num'];
        $isSucess = GoodsCartModel::getInition()->addCart($data);
        
        $this->updateClient($isSucess, '操作', true);
    }
    
    //显示购物车商品
    public function displayGoodsCart()
    {
        //连接工具
        Tool::connect('parseString', null);
        
        $offset = ($_POST['page'] - 1) * $_POST['page_size'];
        
        $data = GoodsCartModel::getInition()->select(array(
            'field' => 'id as cart_id,goods_num,goods_id',
            'where' => array('user_id' => $_SESSION['userId']),
            'order' => 'create_time DESC, update_time DESC',
            'limit' => $offset.','.$_POST['page_size']
        ), GoodsModel::getInitation());
        $data = Tool::command($data);
        $this->updateClient($data, '操作');
    }
    
    //清空购物车商品
    public function clearAllGoods()
    {
        $status = GoodsCartModel::getInition()->delete(array(
            'where' => array('user_id' => $_SESSION['userId'])
        ));
        
        $this->updateClient($status, '操作', true);
    }
    
    ////删除购物车商品
    public function delCartByIds()
    {
        Tool::checkPost($_POST, array('is_numeric' => array('id')), true , array('id')) ? true : $this->ajaxReturnData(null, '400', '参数错误');
        
        $status = GoodsCartModel::getInition()->delete(array(
            'where' => array('id' => $_POST['id'])
        ));
        $this->updateClient($status, '操作', true);
    }
    
    ///增加或减少购物车商品数量
    public function editGoodsNum()
    {
        Tool::checkPost($_POST, array('is_numeric' => array('cart_id', 'goods_num')), true , array('cart_id', 'goods_num')) ? true : $this->ajaxReturnData(null, '400', '参数错误');
        
        $status = GoodsCartModel::getInition()->save($_POST, array(
            'where' => array('id' => $_POST['cart_id'])
        ));
        $this->updateClient($status, '操作', true);
    }
}